from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from datetime import datetime
from typing import Optional

from ..core.database import get_db
from ..models.user_order import UserOrder
from ..models.group_buy_order import GroupBuyOrder
from ..models.stored_value_card import StoredValueCard
from ..models.product import Product
from ..models.store import Store
import random
import string

router = APIRouter(prefix="/api/orders", tags=["orders"])

class PaymentRequest(BaseModel):
    payment_method: str

@router.post("/{order_id}/pay")
async def pay_order(
    order_id: int,
    payment_request: PaymentRequest,
    db: Session = Depends(get_db)
):
    """支付订单"""
    try:
        # 查找订单
        order = db.query(UserOrder).filter(UserOrder.id == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="订单不存在")
        
        # 检查订单状态
        if order.payment_status != 0:
            raise HTTPException(status_code=400, detail="订单状态不正确")
        
        # 更新订单状态为已支付
        order.payment_status = 1
        order.payment_time = datetime.now()
        
        # 更新拼购进度
        group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == order.group_buy_order_id).first()
        if group_buy:
            group_buy.sold_shares += order.shares
            
            # 检查拼购是否完成
            if group_buy.sold_shares >= group_buy.total_shares:
                group_buy.status = 2  # 拼购成功
                group_buy.end_time = datetime.now()
                
                # 为所有参与者生成储值卡
                await generate_stored_value_cards(db, group_buy.id)
        
        db.commit()
        
        return {
            "success": True,
            "message": "支付成功",
            "order_id": order_id,
            "payment_time": order.payment_time
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"支付失败: {str(e)}")

async def generate_stored_value_cards(db: Session, group_buy_id: int):
    """为拼购参与者生成储值卡（按用户合并计算）"""
    try:
        # 获取拼购信息
        group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == group_buy_id).first()
        if not group_buy:
            return
        
        # 获取商品信息
        product = db.query(Product).filter(Product.id == group_buy.product_id).first()
        if not product:
            return
        
        # 获取该拼购的所有订单
        orders = db.query(UserOrder).filter(UserOrder.group_buy_order_id == group_buy_id).all()
        
        # 按用户ID分组，计算每个用户的总参与份数
        user_shares = {}
        for order in orders:
            if order.user_id not in user_shares:
                user_shares[order.user_id] = 0
            user_shares[order.user_id] += order.shares
        
        # 为每个用户生成一张合并的储值卡
        for user_id, total_shares in user_shares.items():
            # 计算该用户的总储值卡金额
            unit_price = float(product.group_buy_price) / group_buy.total_shares
            card_amount = total_shares * unit_price
            
            # 检查是否已存在该用户和该商品的储值卡
            existing_card = db.query(StoredValueCard).filter(
                StoredValueCard.user_id == user_id,
                StoredValueCard.product_id == product.id
            ).first()
            
            if existing_card:
                # 如果已存在，更新金额
                existing_card.original_amount += card_amount
                existing_card.current_amount += card_amount
                print(f"更新用户 {user_id} 的储值卡，增加金额 {card_amount}")
            else:
                # 如果不存在，创建新的储值卡
                card_number = generate_card_number()
                stored_value_card = StoredValueCard(
                    user_id=user_id,
                    store_id=product.store_id,
                    product_id=product.id,
                    card_number=card_number,
                    original_amount=card_amount,
                    current_amount=card_amount,
                    status=1,  # 正常状态
                    valid_until=datetime.now().replace(year=datetime.now().year + 1)  # 一年有效期
                )
                db.add(stored_value_card)
                print(f"为用户 {user_id} 创建新储值卡，金额 {card_amount}")
        
        db.commit()
        
    except Exception as e:
        db.rollback()
        print(f"生成储值卡失败: {str(e)}")

def generate_card_number():
    """生成储值卡号"""
    # 生成16位数字卡号
    return ''.join(random.choices(string.digits, k=16)) 